<template>
  <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
    <el-breadcrumb separator="/">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表管理</el-breadcrumb-item>
  </el-breadcrumb>
  </div>
  <div style="border: 1px solid #ccc;padding: 20px; margin: 10px;">
  <el-button type="success" @click="AddNoe">新增用户</el-button>
   <el-table :data="tableData" style="width: 100%" border>
    <el-table-column fixed type="index" label="序号" width="150" />
    <el-table-column prop="userName" label="用户名" width="120" />
    <el-table-column prop="roleName" label="所属角色" width="120" />
    <el-table-column prop="userSex" label="性别" width="120" >
       <template #default="scope">
        <el-tag style="color: blue;" v-if="scope.row.userSex==false">男</el-tag>
         <el-tag style="color:crimson;" v-if="scope.row.userSex==true">女</el-tag>
       </template>
    </el-table-column>
    <el-table-column prop="provinceName" label="所在省份" width="120" />
     <el-table-column prop="cityName" label="所在市" width="120" />
     <el-table-column prop="countyName" label="所在县" width="120" />
    <el-table-column prop="adderDetail" label="地址详情" width="180" >
        <template #default="scope">
       <el-tooltip :content="scope.row.adderDetail" effect="customized">
            <span>{{scope.row.adderDetail.substr(0,5)}}.......</span>
      </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column prop="creater" label="创建人" width="120" />
    <el-table-column prop="createTime" label="创建日期" width="120" >
      <template #default="scope">
        {{moment(scope.row.createTime).format("YYYY-MM-DD")}}
      </template>
    </el-table-column>
      <el-table-column prop="updater" label="修改人" width="120" />
    <el-table-column prop="updateTime" label="修改日期" width="120" >
      <template #default="scope">
       {{ scope.row.updateTime ? moment(scope.row.updateTime).format("YYYY-MM-DD") : '' }}
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="180">
      <template #default="scope">
        <el-button  type="danger" size="small" @click="Remove(scope.row.id)">删除</el-button>
        <el-button  type="primary" size="small" @click="update(scope.row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <table>
    <tr>
      <td>
        <el-pagination
      v-model:current-page="page.pageindex"
      v-model:page-size="page.pagesize"
      :page-sizes="[15, 16, 17, 18]"
      layout="slot, sizes, prev, pager, next, jumper"
      :total="page.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    >共{{page.TotalCount}}条 当前第{{page.pageindex}}页/共{{page.TotalPage}}页</el-pagination>
      </td>
    </tr>
  </table>
  </div>

<!-- 新增弹窗 -->
    <el-dialog v-model="dialogVisible" title="新增"  width="1000">
         <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户姓名" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
     <el-form-item label="地址" prop="region" style="width: 800px;">
      <el-select v-model="ruleForm.provinceId" placeholder="请选择省份" style="width: 200px;" @change="onProvinceChange">
        <el-option v-for="item in provice"  :label="item.provinceName" :value="item.id" />
      </el-select>
      <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width: 200px;" @change="onCityChange"> 
        <el-option v-for="item in city"   :label="item.cityName" :value="item.id" />
      </el-select>
      <el-select v-model="ruleForm.countyId" placeholder="请选择县" style="width: 200px;" >
        <el-option v-for="item in county"   :label="item.countyName" :value="item.id" />
      </el-select>
    </el-form-item>
     <el-form-item label="部门" prop="deparmentId">
      <el-select v-model="ruleForm.deparmentId " placeholder="Activity zone">
          <el-option label="请选择" :value="0" />
          <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="销售部" :value="3" />
        <el-option label="财务部" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="用户姓别" prop="userSex">
      <el-radio-group v-model="ruleForm.userSex">
        <el-radio :value="false">男</el-radio>
        <el-radio :value="true">女</el-radio>
      </el-radio-group>
    </el-form-item>
     <el-form-item label="详细地址" prop="adderDetail">
      <el-input v-model="ruleForm.adderDetail" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        保存
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>


    </el-dialog>


    <!-- 修改弹窗 -->
    <el-dialog v-model="UpdialogVisible" title="修改"  width="1000">
         <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
  >
    <el-form-item label="用户姓名" prop="userName">
      <el-input v-model="ruleForm.userName" />
    </el-form-item>
    <el-form-item label="地址" prop="region" style="width: 800px;">
      <el-select v-model="ruleForm.provinceId" placeholder="请选择省份" style="width: 200px;" @change="onProvinceChange">
        <el-option v-for="item in provice"  :label="item.provinceName" :value="item.id" />
      </el-select>
      <el-select v-model="ruleForm.cityId" placeholder="请选择市" style="width: 200px;" @change="onCityChange" > 
        <el-option v-for="item in city"   :label="item.cityName" :value="item.id" />
      </el-select>
      <el-select v-model="ruleForm.countyId" placeholder="请选择县" style="width: 200px;" >
        <el-option v-for="item in county"   :label="item.countyName" :value="item.id" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门" prop="deparmentId">
      <el-select v-model="ruleForm.deparmentId " placeholder="Activity zone">
          <el-option label="请选择" :value="0" />
          <el-option label="IT信息部" :value="1" />
        <el-option label="人力资源部" :value="2" />
        <el-option label="销售部" :value="3" />
        <el-option label="财务部" :value="4" />
      </el-select>
    </el-form-item>
    <el-form-item label="用户姓别" prop="userSex">
      <el-radio-group v-model="ruleForm.userSex">
        <el-radio :value="false">男</el-radio>
        <el-radio :value="true">女</el-radio>
      </el-radio-group>
    </el-form-item>
     <el-form-item label="详细地址" prop="adderDetail">
      <el-input v-model="ruleForm.adderDetail" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="UpsubmitForm(ruleFormRef)">
        更新
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>


    </el-dialog>
</template>

<script setup lang="ts">
import axios from 'axios'
import moment  from 'moment'
import {ref,reactive, onMounted}from 'vue'
import { ElMessage, type FormInstance, type FormRules,ElMessageBox } from 'element-plus'
import { id } from 'element-plus/es/locales.mjs'
import { Read,Write } from '@/http/interceptors'

//#region   获取用户列表

const tableData=ref([])

const page=reactive({
    pageindex:1,
    pagesize:15,
    TotalCount:0,
    TotalPage:0,
})
onMounted(()=>{
  GetUser();
})
const GetUser=()=>{
    Read.get("/api/UserGetUserList",{params:page}).then(res=>{
        tableData.value=res.data.pageData
        page.TotalCount=res.data.totalCount
        page.TotalPage=res.data.totalPage
    })
}
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  page.pagesize=val;
  GetUser();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  page.pageindex=val;
  GetUser();
}
//#endregion


//#region   下拉框

onMounted(()=>{
GetProvice();
})

//省份
const provice=ref<any>([])
const GetProvice=()=>{
  Read.get("/api/UserGetProvince",{}).then(res=>{
     provice.value=res.data.data
  })
}
//城市
const city =ref<any>([])
const GetCity=(provinceId:any)=>{
  Read.get("/api/UserGetCity",{ params: { provinceId: provinceId } }).then(res=>{
     city.value=res.data.data 
  })
}
//县级
const county=ref<any>([])
const Getcounty=(CityId:any)=>{
  Read.get("/api/UserGetCounty",{params: { cityId: CityId } }).then(res=>{
     county.value=res.data.data
  })
}

//选择省清空市县
const onProvinceChange=(provinceId:any)=>{
 ruleForm.cityId = '';
  ruleForm.countyId = '';
  city.value = [];
  county.value = [];
  if (provinceId) {
    GetCity(provinceId);
  }
}
//当选择市清空县
const onCityChange=(CityId:any)=>{
ruleForm.countyId = '';
  county.value = [];
  if (CityId) {
    Getcounty(CityId);
  }
}


//#endregion


//#region  新增
const dialogVisible = ref(false)
const AddNoe=()=>{
dialogVisible.value=true;
ruleForm.userName="";
ruleForm.cityId='',
ruleForm.countyId='',
ruleForm.deparmentId=0,
ruleForm.userSex=false
ruleForm.adderDetail=""
}



const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "userName": "",
  "userPwd": "12345678",
  "userSex":false,
  "provinceId": '',
  "cityId": '',
  "countyId": '',
  "adderDetail": "",
   "deparmentId": 0,
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules>({
  userName: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
  ],
  adderDetail: [
    { required: true, message: '地址详情不能为空', trigger: 'blur' },
  ],
  userSex: [
    { required: true, message: '性别必选', trigger: 'change' },
  ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.post("/api/UserCreateUser",ruleForm).then(res=>{
        if(res.data.code==200)
        {
          dialogVisible.value=false
          ruleForm.userName=""
          ruleForm.userSex=false;
          ruleForm.adderDetail="";
          ruleForm.provinceId='';
          ruleForm.countyId='';
          ruleForm.cityId=''
          provice.value=[];
          GetUser();
          ElMessage.success(res.data.message)
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}


//#endregion


//#region   删除
const Remove=(id:any)=>{
    ElMessageBox.confirm(
    '确认删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Write.delete("/api/UserDeleteUser",{params:{id:id}}).then(res=>{
        if(res.data.code==200)
        {
          ElMessage.success(res.data.message)
          GetUser();
        }
        else
        {
           ElMessage.error(res.data.message)
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除操作已取消',
      })
    })

}

//#endregion


//#region   修改

const UpdialogVisible=ref(false)

//反填信息
const update=(row:any)=>{
UpdialogVisible.value=true
Object.assign(ruleForm,row);
ruleForm.deparmentId=row.deparmentId
GetCity(row.provinceId)
Getcounty(row.cityId)
}

const UpsubmitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!')
      Write.put("/api/UserUpdateUser",ruleForm).then(res=>{
        if(res.data.code==200)
        {
          UpdialogVisible.value=false
          ruleForm.userName=""
          ruleForm.userSex=false;
          ruleForm.adderDetail="";
          ruleForm.provinceId='';
          ruleForm.countyId='';
          ruleForm.cityId=''
          provice.value=[];
          GetUser();
          ElMessage.success(res.data.message)
        }
        else
        {
          ElMessage.error(res.data.message)
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}
//#endregion
</script>

<style>
.el-popper.is-customized {
  /* Set padding to ensure the height is 32px */
  padding: 6px 12px;
  background: linear-gradient(90deg, rgb(159, 229, 151), rgb(204, 229, 129));
}

.el-popper.is-customized .el-popper__arrow::before {
  background: linear-gradient(45deg, #b2e68d, #bce689);
  right: 0;
}
</style>